package cn.aicnn.chatssespringboot.controller;

import cn.aicnn.chatssespringboot.common.CommonResponse;
import cn.aicnn.chatssespringboot.service.NewChatService;
import cn.aicnn.chatssespringboot.vo.ChatVO;
import cn.aicnn.chatssespringboot.vo.TextQuestionVO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;


@RestController
public class newChatController {
    private static final Logger logger = Logger.getLogger(newChatController.class);

    @Autowired
    NewChatService newChatService;

    @PostMapping("/api/newChat/{username}")
    public CommonResponse<ChatVO> newChat(@PathVariable String username, @RequestParam("fileList") MultipartFile[] fileList) {
        if (fileList == null || fileList.length == 0) {
            return CommonResponse.createForError("没有上传文件");
        }

        MultipartFile file = fileList[0]; // 处理第一个文件
        logger.info("接收到的文件: " + file.getOriginalFilename());

        // 使用 UTF-8 编码读取文件内容
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            logger.error("读取文件时发生错误: ", e);
            return CommonResponse.createForError("文件读取失败");
        }

        String question = content.toString().trim(); // 去除首尾空格
        logger.info("提问内容: " + question);

        // 处理提问逻辑
        ChatVO chatVO = newChatService.newChat(username, question);
        if (chatVO == null) {
            return CommonResponse.createForError("处理请求时发生错误");
        }

        return CommonResponse.createForSuccess("成功", chatVO);
    }

    @GetMapping("/api/chat/userModel")
    public CommonResponse<Object> userModel(){
        return newChatService.userModel1();
    }

    @PostMapping("/api/chat/text/{username}")
    public CommonResponse<ChatVO> textNewChat(@PathVariable String username, @RequestBody TextQuestionVO textQuestionVO){
        logger.info("textQuestion:" + textQuestionVO);
        // 处理提问逻辑
        ChatVO chatVO = newChatService.newChat(username, textQuestionVO.getQuestion());
        if (chatVO == null) {
            return CommonResponse.createForError("处理请求时发生错误");
        }

        return CommonResponse.createForSuccess("成功", chatVO);
    }

}
